//
//  FCPExtensions.swift
//  flutter_carplay
//
//  Created by Oğuzhan Atalay on 21.08.2021.
//

extension UIImage {
  convenience init?(withURL url: URL) throws {
    let imageData = try Data(contentsOf: url)
    self.init(data: imageData)
  }
  
  @available(iOS 14.0, *)
  func fromFlutterAsset(name: String) -> UIImage {
    let key: String? = SwiftFlutterCarplayPlugin.registrar?.lookupKey(forAsset: name)
    let image: UIImage? = UIImage(imageLiteralResourceName: key!)
    return image ?? UIImage(systemName: "questionmark")!
  }

  //同步获取图片
  @available(iOS 14.0, *)
  func getIcon(name: String) -> UIImage {
    return getImage(name:name) ?? UIImage(systemName: "questionmark")!
  }
    
  ///异步获取图片
  @available(iOS 14.0, *)
  func asyncGetImage(name:String, completionHandler: @escaping(createResult) -> Void ) {
    DispatchQueue.global().async {
        //模拟Http线程内请求  阻塞3秒
        let image = UIImage().getImage(name: name)
        if(image == nil){
          completionHandler(.error(errorStr: "请求失败 name = \(name)"))
        }else {
          completionHandler(.success(image: image!))
        }
    }
  }
    
  @available(iOS 14.0, *)
  private func getImage(name: String) -> UIImage? {
    var image: UIImage?
    if name.starts(with: "assets"){
      let key: String? = SwiftFlutterCarplayPlugin.registrar?.lookupKey(forAsset: name)
      image = UIImage(imageLiteralResourceName: key!)
    } else if name.starts(with: "http") {
      let url = URL(string: name)
      do {
        image = try UIImage(withURL: url!)
      }catch { }
    } else {
      image = UIImage(systemName: name)
    }
    return image ?? nil
  }
  
  ///请求成功返回自定义描述[successStr]，请求失败则返回自定义描述[errorStr]
  enum createResult {
    case success(image:UIImage)
    case error(errorStr:String)
  }
    
}

extension String {
  func match(_ regex: String) -> [[String]] {
    let nsString = self as NSString
    return (try? NSRegularExpression(pattern: regex, options: []))?.matches(in: self, options: [], range: NSMakeRange(0, nsString.length)).map { match in
        (0..<match.numberOfRanges).map { match.range(at: $0).location == NSNotFound ? "" : nsString.substring(with: match.range(at: $0)) }
    } ?? []
  }
}
